<template>
  <el-container>
    <el-header>
      <div class="left-panel">
        <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            @click="handleAdd"
        >新增
        </el-button>
        <el-button
            type="success"
            plain
            icon="el-icon-edit"
            :disabled="single"
            @click="handleUpdate"
        >修改
        </el-button>
        <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            :disabled="multiple"
            @click="handleDelete"
        >删除
        </el-button>
        <el-button
            type="warning"
            plain
            icon="el-icon-delete"
            :disabled="single"
            @click="handleAuth"
        >权限设置
        </el-button>
      </div>
      <div class="right-panel">
        <jcx-table-bar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></jcx-table-bar>
      </div>
    </el-header>

    <el-main>
      <el-form :model="queryParams" ref="queryForm" size="default" :inline="true" v-show="showSearch"
               label-width="68px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="角色名称" prop="roleName">
              <el-input
                  v-model="queryParams.roleName"
                  placeholder="请输入角色名称"
                  clearable
                  @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="角色状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="角色状态" clearable>
                <el-option key="1" label="启用" :value="true"/>
                <el-option key="0" label="停用" :value="false"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-table ref="table" v-loading="loading" :data="roleList" row-key="roleId"
                @selection-change="handleSelectionChange"
                :stripe="config.stripe" :border="config.border" :size="config.size" style="width: 100%">
        <el-table-column type="selection"></el-table-column>
        <el-table-column label="角色标识" align="center" prop="roleCode" v-if="columns[0].visible"></el-table-column>
        <el-table-column label="角色名称" align="center" prop="roleName" v-if="columns[1].visible"></el-table-column>
        <el-table-column label="状态" align="center" prop="status" v-if="columns[2].visible">
          <template #default="scope">
            <el-tag v-if="scope.row.status" type="success">启用</el-tag>
            <el-tag v-if="!scope.row.status" type="danger">停用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" v-if="columns[3].visible"></el-table-column>
        <el-table-column label="备注" align="center" prop="remark" v-if="columns[4].visible"></el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="props">
            <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(props.row)"
            >修改
            </el-button>
            <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(props.row)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <jcx-page
          v-show="total>0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
      ></jcx-page>

      <el-dialog destroy-on-close append-to-body width="900px" :title="title" v-model="open"
                 :close-on-click-modal="false" @closed="cancel">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="角色标识" prop="roleCode">
                <el-input v-model="form.roleCode" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="form.roleName" clearable></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="是否有效" prop="status">
                <el-switch v-model="form.status" :active-value="true" :inactive-value="false"></el-switch>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="排序" prop="sort">
                <el-input-number v-model="form.sort" :precision="2" :min="1" :step="0.01"
                                 controls-position="right"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" clearable type="textarea"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <el-button type="primary" :loading="saveing" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </template>
      </el-dialog>

      <el-dialog destroy-on-close append-to-body width="500px" title="角色权限设置" v-model="visible"
                 :close-on-click-modal="false" @closed="authCancel">
        <el-tabs tab-position="top">
          <el-tab-pane label="分配菜单权限">
            <el-form label-position="left" label-width="100px">
              <el-form-item label="菜单权限">
                <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选
                </el-checkbox>
                <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠
                </el-checkbox>
                <el-checkbox v-model="menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')">父子联动
                </el-checkbox>
                <div class="treeMain" style="width: 100%;">
                  <el-tree
                      show-checkbox
                      class="tree-border"
                      ref="menu"
                      node-key="menuId"
                      :data="menuList"
                      :props="menuProps"
                      :check-strictly="!menuCheckStrictly"
                      empty-text="加载中，请稍候"
                  ></el-tree>
                </div>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="分配数据权限">
            <el-form label-position="left" label-width="100px">
              <el-form-item label="规则类型">
                <el-select v-model="currentRole.dataScope" placeholder="请选择" @change="dataScopeSelectChange">
                  <el-option label="全部数据权限" value="1"></el-option>
                  <el-option label="自定数据权限" value="2"></el-option>
                  <el-option label="本部门数据权限" value="3"></el-option>
                  <el-option label="本部门及以下数据权限" value="4"></el-option>
                  <el-option label="仅本人数据权限" value="5"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item v-show="currentRole.dataScope==='2'" label="数据权限">
                <el-checkbox v-model="deptNodeAll" @change="handleCheckedTreeNodeAll($event, 'dept')">全选/全不选
                </el-checkbox>
                <el-checkbox v-model="deptExpand" @change="handleCheckedTreeExpand($event, 'dept')">展开/折叠
                </el-checkbox>
                <el-checkbox v-model="deptCheckStrictly" @change="handleCheckedTreeConnect($event, 'dept')">父子联动
                </el-checkbox>
                <div class="treeMain" style="width: 100%;">
                  <el-tree
                      show-checkbox
                      class="tree-border"
                      ref="dept"
                      node-key="deptId"
                      :data="deptList"
                      :props="deptProps"
                      :check-strictly="!deptCheckStrictly"
                      empty-text="加载中，请稍候"
                  ></el-tree>
                </div>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
        <template #footer>
          <el-button @click="authCancel">取 消</el-button>
          <el-button :loading="saveing" type="primary" @click="authSubmit">保 存</el-button>
        </template>
      </el-dialog>
    </el-main>
  </el-container>
</template>

<script>

export default {
  name: "Role",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 保存遮罩层
      saveing: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 打开的权限设置 Role 对象
      currentRole: {
        dataScope: '1'
      },
      // 部门列表数据
      roleList: [],
      // 菜单列表数据
      menuList: [],
      // 部门列表数据
      deptList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示权限设置
      visible: false,
      // 分页总条数
      total: 0,
      // 查询参数
      queryParams: {
        roleName: undefined,
        status: undefined,
        pageNum: 1,
        pageSize: 10
      },
      // 表单参数
      form: {},
      // 菜单子父关系
      menuProps: {
        label: (data) => {
          return data.meta.title
        }
      },
      // 部门子父关系
      deptProps: {
        label: (data) => {
          return data.deptName
        }
      },
      // 展开/折叠
      menuExpand: false,
      deptExpand: false,
      // 全选/全不选
      menuNodeAll: false,
      deptNodeAll: false,
      // 父子联动
      menuCheckStrictly: true,
      deptCheckStrictly: true,
      // 表单校验
      rules: {
        roleCode: [
          {required: true, message: '请输入角色标识', trigger: 'blur'}
        ],
        roleName: [
          {required: true, message: '请输入角色名称', trigger: 'blur'}
        ],
        status: [
          {required: true, message: '请选择角色状态', trigger: 'blur'}
        ]
      },
      // 表格配置
      config: {
        // 表格大小
        size: "default",
        // 表格边框
        border: true,
        // 表格斑马图纹
        stripe: true
      },
      columns: [
        {key: 0, label: `角色标识`, visible: true},
        {key: 1, label: `角色名称`, visible: true},
        {key: 2, label: `状态`, visible: true},
        {key: 3, label: `创建时间`, visible: false},
        {key: 4, label: `备注`, visible: true}
      ],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询部门列表 */
    getList() {
      this.loading = true;
      if (this.menuList.length === 0) {
        this.$API.menu.pageListMenu.get({status: true}).then(response => {
          if (response.status) {
            this.menuList = response.data.records
          } else {
            this.$message.warning(response.msg);
          }
        });
      }
      if (this.deptList.length === 0) {
        this.$API.dept.pageListDept.get({status: true}).then(response => {
          if (response.status) {
            this.deptList = response.data.records
          } else {
            this.$message.warning(response.msg);
          }
        });
      }
      this.$API.role.pageListRole.get(this.queryParams).then(response => {
        if (response.status) {
          this.roleList = response.data.records
          this.total = response.data.total
        } else {
          this.$message.warning(response.msg);
        }
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.saveing = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        roleId: "",
        roleCode: "",
        roleName: "",
        remark: "",
        status: true,
        sort: 1
      };
      this.$nextTick(() => {
        if (this.$refs['form']) {
          this.$refs['form'].clearValidate();
          this.$refs['form'].resetFields();
        }
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs["queryForm"].resetFields();
      this.handleQuery();
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.roleId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加角色";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const roleId = row.roleId || this.ids
      this.$API.role.getRoleById.get(roleId).then(response => {
        if (response.status) {
          this.form = response.data;
          this.open = true;
          this.title = "修改角色";
        } else {
          this.$message.warning(response.msg);
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.saveing = true;
          // 如果 ID 存在就是更新
          if (this.form.roleId) {
            this.$API.role.editRole.put(this.form).then(response => {
              if (response.status) {
                this.$message.success(response.msg);
                this.saveing = false;
                this.open = false;
                this.getList();
              } else {
                this.$alert(response.msg, "提示", {type: 'error'});
                this.saveing = false;
              }
            });
          } else {
            // 不存在就是新增
            this.$API.role.addRole.post(this.form).then(response => {
              if (response.status) {
                this.$message.success(response.msg);
                this.saveing = false;
                this.open = false;
                this.getList();
              } else {
                this.$alert(response.msg, "提示", {type: 'error'});
                this.saveing = false;
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const roleIds = row.roleId ? [row.roleId] : this.ids;
      this.$confirm(`确定删除选中的 ${roleIds.length} 项吗？`, '提示', {
        type: 'warning'
      }).then(() => {
        this.$API.role.delRoles.delete(roleIds).then(response => {
          if (response.status) {
            this.$message.success(response.msg);
            this.getList();
          } else {
            this.$alert(response.msg, "提示", {type: 'error'});
          }
        });
      }).catch(() => {
      })
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      if (type === 'menu') {
        let treeList = this.menuList;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].menuId].expanded = value;
        }
      } else if (type === 'dept') {
        let treeList = this.deptList;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.dept.store.nodesMap[treeList[i].deptId].expanded = value;
        }
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type === 'menu') {
        this.$refs.menu.setCheckedNodes(value ? this.menuList : []);
      } else if (type === 'dept') {
        this.$refs.dept.setCheckedNodes(value ? this.deptList : []);
      }
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      if (type === 'menu') {
        this.menuCheckStrictly = !!value;
      } else if (type === 'dept') {
        this.deptCheckStrictly = !!value;
      }
    },
    /** 不是自定义数据权限时候删除选中 */
    dataScopeSelectChange(value) {
      if (value !== '2') {
        this.$refs.dept.setCheckedKeys([]);
      }
    },
    /** 打开权限设置面板 */
    async handleAuth() {
      let response = await this.$API.role.getRoleById.get(this.ids);
      if (response.status) {
        this.currentRole = response.data;
        // 设置默认选中
        this.$nextTick(() => {
          // 菜单的默认选中
          let platformRoleMenuQueryDtos = this.currentRole.platformRoleMenuQueryDtos
          platformRoleMenuQueryDtos.forEach((platformRoleMenuQueryDto) => {
            this.$nextTick(() => {
              this.$refs.menu.setChecked(platformRoleMenuQueryDto.menuId, true, false);
            })
          })
          // 部门的默认选中
          if (this.currentRole.dataScope === '2') {
            let platformDeptRoleQueryDtos = this.currentRole.platformDeptRoleQueryDtos
            platformDeptRoleQueryDtos.forEach((platformDeptRoleQueryDto) => {
              this.$nextTick(() => {
                this.$refs.dept.setChecked(platformDeptRoleQueryDto.deptId, true, false);
              })
            })
          }
        });
        this.visible = true;
      }
    },
    /** 关闭权限设置面板 */
    authCancel() {
      this.visible = false;
      this.menuExpand = false;
      this.deptExpand = false;
      this.menuNodeAll = false;
      this.deptNodeAll = false;
      this.menuCheckStrictly = true;
      this.deptCheckStrictly = true;
    },
    /** 权限设置保存 */
    authSubmit() {
      let exists = false;
      let checkedMenuIds = this.$refs.menu.getCheckedKeys();
      for (let i = 0; i < checkedMenuIds.length; i++) {
        if (this.currentRole.dashboardMenuId === checkedMenuIds[i]) {
          exists = true;
        }
      }
      if (!exists) {
        this.$alert("控制台菜单必须存在", "提示", {type: 'error'});
        return;
      }
      // 更新 roleMenu
      this.$API.role.updateRoleMenuAndDataAuth.put({
        roleId: this.currentRole.roleId,
        dataScope: this.currentRole.dataScope,
        menuIds: this.$refs.menu.getCheckedKeys().concat(this.$refs.menu.getHalfCheckedKeys()),
        deptIds: this.currentRole.dataScope !== '2' ? [] : this.$refs.dept.getCheckedKeys().concat(this.$refs.dept.getHalfCheckedKeys())
      }).then(response => {
        if (response.status) {
          this.$message.success(response.msg);
          this.visible = false;
        } else {
          this.$alert(response.msg, "提示", {type: 'error'});
        }
      });
    }
  }
};
</script>

<style scoped>
.treeMain {
  height: 280px;
  overflow: auto;
  border: 1px solid #dcdfe6;
  margin-bottom: 10px;
}
</style>
